<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Test</title>
</head>
<body>

<label for="text"></label><input id="text" type="text"/>
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="message"></div>
</body>

<script type="text/javascript">
    let websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:9090/websocket/123456");
    } else {
        alert('Not support websocket');
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        showMessage("打开连接失败");
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        showMessage("打开连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        showMessage(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        showMessage("关闭连接成功");
    }

    //监听窗口关闭事件，当窗口关闭时，主动关闭WebSocket连接
    window.onbeforeunload = function () {
        websocket.close();
    }

    function showMessage(message) {
        document.getElementById('message').innerHTML += message + '<br/>';
    }

    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function sendMessage() {
        const message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>